import { useState, type ChangeEvent, type FC } from "react"
import styles from "./editHeader.module.scss"
import { LeftOutlined, EditOutlined,  ArrowUpOutlined, DeleteOutlined, EyeOutlined, LockOutlined, CopyOutlined, BlockOutlined, UpOutlined, DownOutlined, RedoOutlined, LoadingOutlined, CheckOutlined, UndoOutlined, ClearOutlined } from "@ant-design/icons"
import { useNavigate, useParams } from "react-router-dom"
import { Space, Button, Tooltip, message, Modal, Input } from "antd"
import { useComponentStore, useStore, useTemporalStore } from "@/store"
import { useDebounceEffect, useKeyPress, useRequest } from "ahooks"
import { updateQuestionApi } from "@/apis/question"
import type {  questionComponentType } from "@/utils/type"
import { nanoid } from "nanoid"


const selectNextId = (id: string, list: questionComponentType[]) => {
  const index = list.findIndex(item => item.fe_id === id)
  if (index < 0) {
    return ''
  }
  if (index === list.length - 1) {
    if (list.length != 1)
      return list[index - 1].fe_id
    return ''
  }
  return list[index + 1].fe_id
}


// 标题组件及逻辑
const TitleElem = () => {
  const [editStatus, setEditStatus] = useState(false)
  const store = useStore()
  const { title, js, css, desc } = store.pageInfo
  //修改标题
  const handleChangeTitle = (e: ChangeEvent<HTMLInputElement>) => {
    store.setPageInfo({ title: e.target.value.trim(), js, css, desc })
  }
  if (editStatus)
    return (
      <Input
        onChange={handleChangeTitle}
        value={title}
        onPressEnter={() => setEditStatus(false)}
        onBlur={() => setEditStatus(false)}
      />
    )
  return (
    <div style={{ display: 'flex', alignItems: 'center' }}>
      <span className={styles.ellipsis}>{title}</span>
      <Button icon={<EditOutlined />} type="text" onClick={() => setEditStatus(true)}></Button>
    </div>
  )
}

const EditHeader: FC = () => {
  const {undo,redo} = useTemporalStore.getState()
  const {copiedComponent,setCopiedComponent, selectedId,setSelectedId} = useStore()
  const { setComponentList, moveComponent, addComponent, deleteComponent, hiddenComponent, lockComponent, componentList } = useComponentStore()
  const {pageInfo} = useStore()
  const index = componentList.findIndex(item => item.fe_id === selectedId)
  const nav = useNavigate()

  //删除问卷
  const handleDelete = () => {
    if (!selectedId) return message.warning("请先选择组件")
    //执行删除逻辑
    deleteComponent(selectedId)
    setSelectedId(selectNextId(selectedId, componentList))
    message.success("删除成功")
  }
  //显示/隐藏问卷
  const handleHidden = () => {
    if (!selectedId) return message.warning("请先选择组件")

    hiddenComponent(selectedId)
    message.success("隐藏成功")

  }
  //锁定问卷
  const handleLock = () => {
    if (!selectedId) return message.warning("请先选择组件")
    //执行锁定逻辑
    lockComponent(selectedId)
    message.success("锁定成功")
  }

  //复制问卷
  const handleCopy = () => {
    if (!selectedId) return message.warning("请先选择组件")
    //执行复制逻辑
    const item = componentList.find(item => item.fe_id === selectedId) as questionComponentType
    setCopiedComponent(item)
    message.success("复制成功")
  }

  //粘贴问卷
  const handlePaste = () => {
    if (!copiedComponent) return message.warning("请先复制组件")
    //执行粘贴逻辑
    addComponent({ ...copiedComponent, fe_id:nanoid()},selectedId)
    message.success("粘贴成功")
  }

  //向上移动
  const handleUp = () => {
    if (!selectedId) return message.warning({
      content: "请先选择组件",
      duration: 0.5
    })
    if (index === 0) return message.warning({
      content: "已在顶部",
      duration: 0.5
    })
    moveComponent(index, index - 1)

  }

  //向下移动
  const handleDown = () => {
    if (!selectedId) return message.warning({
      content: "请先选择组件",
      duration: 0.5
    })
    if (index === componentList.length - 1) return message.warning({
      content: "已在底部",
      duration: 0.5
    })
    moveComponent(index, index + 1)
  }

  //撤回问卷
  const handleUndo = () => {
    undo()
   
  }

  //重做
  const handleRedo = ()=>{
    redo()
   
  }

  //重做问卷
  const handleClear = () => {
    Modal.confirm({
      title: '确认清空',
      content: '是否确认清空当前问卷？',
      onOk: () => {
        setComponentList([])
      }
    })

  }
  //保存问卷逻辑
  const {id} = useParams()
  const {loading,run:save} = useRequest(async()=>{
    if(!id) return 
    await updateQuestionApi(id,{componentList,...pageInfo})
  },{
    manual:true,
    onSuccess:()=>{
      message.success("保存成功")
    }
  })

  //点击保存按钮
  const handleSave = () =>{
    if(!loading) 
    save()
  }

  //监听ctrl+s或meta+s保存问卷
  useKeyPress(['ctrl.s','meta.s'],(e:KeyboardEvent)=>{
    //阻止默认保存行为
    e.preventDefault()
    if(!loading) save()
  })

  //自定保存(不是定时器保存)
  useDebounceEffect(()=>{
    save()
  },[pageInfo,componentList],{wait:10000})

  // 发布问卷
  const {loading:loadingPub,run:pub} = useRequest(async()=>{
    if(!id) return 
    await updateQuestionApi(id,{componentList,...pageInfo,isPublished:true})
  },{
    manual:true,
    onSuccess:()=>{
      message.success("发布成功")
      nav('/question/stat/'+id)
    }
  })
  const handlePublish = ()=>{
    if(!loadingPub)
     pub()
  }




  return (
    <div className={styles.container}>
      <div className={styles.left}>
        <Space size="large">
          <Space className={styles.back} onClick={() => nav(-1)} >
            <LeftOutlined />
            <span>返回</span>
          </Space>
          <Space>
            <TitleElem></TitleElem>
          </Space>
        </Space>
      </div>

      <div className={styles.center}>
        <Tooltip title="删除">
          <Button onClick={handleDelete} shape="circle" icon={<DeleteOutlined />}></Button>
        </Tooltip>
        <Tooltip title="隐藏">
          <Button onClick={handleHidden} shape="circle" icon={<EyeOutlined />}></Button>
        </Tooltip>
        <Tooltip title="锁定">
          <Button style={{ backgroundColor: componentList[index]?.isLocked ? 'skyblue' : '' }} onClick={handleLock} shape="circle" icon={<LockOutlined />}></Button>
        </Tooltip>
        <Tooltip title="复制">
          <Button onClick={handleCopy} shape="circle" icon={copiedComponent ? <CopyOutlined /> : <CopyOutlined />}></Button>
        </Tooltip>
        <Tooltip title="粘贴">
          <Button disabled={copiedComponent ? false : true} onClick={handlePaste} shape="circle" icon={<BlockOutlined />}></Button>
        </Tooltip>
        <Tooltip title="向上">
          <Button disabled={index === 0 || !selectedId} onClick={handleUp} shape="circle" icon={<UpOutlined />}></Button>
        </Tooltip>
        <Tooltip title="向下">
          <Button disabled={index === componentList.length - 1 || !selectedId} onClick={handleDown} shape="circle" icon={<DownOutlined />}></Button>
        </Tooltip>
        <Tooltip title="撤回">
          <Button onClick={handleUndo} shape="circle" icon={<UndoOutlined />}></Button>
        </Tooltip>
         <Tooltip title="重做">
          <Button onClick={handleRedo} shape="circle" icon={<RedoOutlined />}></Button>
        </Tooltip>
        <Tooltip title="清空">
          <Button onClick={handleClear} shape="circle" icon={<ClearOutlined />}></Button>
        </Tooltip>
      </div>
      <div className={styles.right}>
        <Button icon={loading ? <LoadingOutlined /> : <CheckOutlined />} onClick={handleSave}>保存</Button>
        <Button icon={loadingPub ? <LoadingOutlined /> : <ArrowUpOutlined />} type="primary" onClick={handlePublish}>发布</Button>
      </div>
    </div>

  )
}



export default EditHeader